<?php

namespace app\queue\stomp;

use app\queue\BaseConsumer;
use Webman\Stomp\RetryAbleConsumer;
use common\service\TaskMemberService;
use common\exception\QueueNeedRetryException;

/**
 * 工单用户发生变化
 * 异步同步到会话中
 */
class TaskWorkOrderChangeUserToChatConsumer extends BaseConsumer implements RetryAbleConsumer
{

    // 要消费的队列名
    public $queue = 'task_work_order_change_user_to_chat';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';

    /**
     * @param $data
     * @return void
     * @throws \Exception
     */
    public function doConsume($data)
    {
        if ($data['type'] === 'add') {
            TaskMemberService::getInstance()->taskWorkOrderUserAddIm($data['user_id'], $data['task_work_order_id']);
        } else if ($data['type'] === 'delete') {
            TaskMemberService::getInstance()->taskWorkOrderDeleted($data['user_id'], $data['task_work_order_id']);
        }
    }

    /**
     * 重试间隔
     * @return int
     */
    public function getTtr()
    {
        return 10;
    }

    /**
     * 能否重试
     * @param $attempt
     * @param $error
     * @return bool
     */
    public function canRetry($attempt, $error)
    {
        trace(format_exception_info($error), 'ERR');
        if ($error instanceof QueueNeedRetryException) {
            return true;
        }
        return $attempt <= 10;
    }
}
